<?php

final class Response {
    use \Lib\Traits\StaticClass;

    /**
     * 返回数据
     *
     * @param string|array|\Base\Model\AbstractModel $data
     * @param string $msg
     * @param int $code
     *
     * @return false
     */
    public static function data($data, $msg = null, $code = 200) {

        $resource = ['status' => true, 'code'   => (int)$code];
        $resource['msg']  = $msg;
        $resource['data'] = is_array($data)
                            ? $data
                            : ($data instanceof \Base\Model\AbstractModel ? $data->toArray() : (string)$data);

        header('Content-type: application/json; charset=utf-8');
        echo \json_encode($resource);

        return false;
    }

    /**
     * Error
     *
     * @param string $msg
     * @param int $code
     *
     * @return false
     */
    public static function error($msg = null, $code = 0) {
        $resource = [
            'status' => false,
            'code'   => (int)$code,
            'msg'    => (string)$msg
        ];

        header('Content-type: application/json; charset=utf-8');
        echo \json_encode($resource);

        return false;
    }

    /**
     * 回调
     *
     * @param array|string $data
     * @param string $callback
     * @return boolean
     */
    public static function callback($data, $callback) {
        if(!!$callback && preg_match('/^[a-zA-Z_][a-zA-Z0-9_\.]*$/', (string)$callback)) {
            $resource = is_array($data)
                    ? $data
                    : ($data instanceof \Base\Model\AbstractModel ? $data->toArray() : (string)$data);

            header('Content-type: application/javascript; charset=utf-8');
            echo $callback . '(' . \json_encode($resource) . ');';

            return false;
        }

        return self::error('invalid callback');
    }

    public static function wxdata($data, $msg = null, $code = 200) {
        $request = \Yaf\Dispatcher::getInstance()->getRequest();
        $callback = $request->get('callback');

        $resource = ['status' => true, 'code'   => (int)$code];
        $resource['msg']  = $msg;
        $resource['data'] = is_array($data)
            ? $data
            : ($data instanceof \Base\Model\AbstractModel ? $data->toArray() : (string)$data);

        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        echo $callback. '(' . \json_encode($resource) . ')';

        return false;
    }

    public static function wxerror($msg = null, $code = 0) {
        $request = \Yaf\Dispatcher::getInstance()->getRequest();
        $callback = $request->get('callback');

        $resource = [
            'status' => false,
            'code'   => (int)$code,
            'msg'    => (string)$msg
        ];

        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        echo $callback. '(' . \json_encode($resource) . ')';

        return false;
    }
}
